package com.zcy.gift.rocketmq.listener.transaction;

import com.alibaba.fastjson.JSONArray;
import com.zcy.gift.constant.GiftConstant;
import com.zcy.gift.dto.SpuOnsaleDto;
import com.zcy.gift.service.IGoodsSpuService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author lucker
 * @date 2024/2/15 0:57
 */
@Component
@RocketMQTransactionListener(txProducerGroup = GiftConstant.GIFT_OFFSALE_TX_PRODUCER_GROUP)
public class GiftSpuOffsaleLocalTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IGoodsSpuService goodsSpuService;

    /**
     * 执行本地事务
     * @param message
     * @param o
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        byte[] payload = (byte[]) message.getPayload();
        List<Long> ids = JSONArray.parseArray(new String(payload), Long.class);

        try {
            goodsSpuService.spuOffsaleExecuteLocalTransaction(ids);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 回查本地事务
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        byte[] payload = (byte[]) message.getPayload();
        List<Long> ids = JSONArray.parseArray(new String(payload), Long.class);
        try {
            Boolean flag = goodsSpuService.spuOffsaleCheckLocalTransaction(ids);
            if (flag) {
                return RocketMQLocalTransactionState.COMMIT;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
